import axios from 'axios'
import {
  Toast
} from 'vant'
/**
 * 跳转登录
 */
const skipLogin = () => {
  BmacJSBridge.call(
    "startApp", {
      appId: "00000060",
      closeCurrentApp: true,
      popNum: "-1",
      type: "1"
    },
    (result) => {

    }
  );
};
/**
 * 加密
 */
const encrypt = (encryptParam) => {
  return new Promise((resolve, reject) => {
    BmacJSBridge.call("encryptDataWithRSA3", encryptParam, (encryptData) => {
      try {
        resolve(encryptData)
      } catch (error) {
        reject(error)
      }
    })
  })
}
/**
 * 解密
 */
const decrypt = (decryptParam) => {
  return new Promise((resolve, reject) => {
    BmacJSBridge.call(
      "decryptDataWithRSA3", {
        decryptParam: decryptParam
      },
      (decryData) => {
        try {
          resolve(decryData)
        } catch (error) {
          reject(error)
        }
      }
    )
  })
}
export function httpRequest(url, tokenStr, data) {
  return new Promise((resolve, reject) => {
    BmacJSBridge.call("getBasicInfo", (result) => {
      let version = result.deviceData.version;
      let ObjcetData = Object.assign({
        app_Version: version
      }, data)
      // console.error('AppVersion---->',ObjcetData);
      encrypt(ObjcetData).then(encryptRes => {
        BmacJSBridge.call('obtainClientBaseUrl', async (urlData) => {
          if (urlData.pay3BaseUrl.startsWith('https')) {
            axios({
              method: 'POST',
              url: `${urlData.pay3BaseUrl}/` + url,
              timeout: 70000,
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `${urlData.Authorization}`,
                'wolf-auth': tokenStr
              },
              data: encryptRes.encryptedData
            }).then(res => {
              if (res.status == 200) {
                decrypt(res.data).then(resD => {
                  resolve(resD.encryptedData);
                });
              } else {
                reject(res);
              }
            }).catch(err => {
              if (err.response && err.response.status && err.response.status == 401) {
                skipLogin();
              } else {
                if (!err.response) {
                  reject()
                  Toast('网络开小差')
                  return
                } 
                decrypt(err.response.data).then(resD_1 => {
                  reject(resD_1.encryptedData);
                  let error = resD_1.encryptedData.message || resD_1.encryptedData.msg || '网络开小差'
                  Toast(error)
                  console.log(resD_1.encryptedData, '错误数据');
                });
              }
            })
          } else {
            reject()
            Toast('请求不正确')
          }
        })
      })
    })
  })
}
